package com.gx.smart.building.ui.splash.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.gx.smart.base.BaseMVVMFragment;
import com.gx.smart.building.databinding.SplashFragmentBinding;
import com.gx.smart.building.ui.home.activity.MainActivity;
import com.gx.smart.building.ui.login.activity.LoginActivity;
import com.gx.smart.building.ui.login.viewmodel.LoginViewModel;
import com.gx.smart.common.util.AppConfig;

public class SplashFragment extends BaseMVVMFragment<SplashFragmentBinding, LoginViewModel> {


    public static final int DELAY_TIME = 1000 * 1;

    @Override
    protected Class<LoginViewModel> onBindViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected SplashFragmentBinding onBindViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) {
        return SplashFragmentBinding.inflate(inflater, parent, false);
    }

    @Override
    protected void initView(@NonNull View view) {
        view.postDelayed(() -> {
            if (getActivity() == null || !ActivityUtils.isActivityAlive(getActivity())) {
                return;
            }

            String token = SPUtils.getInstance().getString(AppConfig.LOGIN_TOKEN, "");
            if (!TextUtils.isEmpty(token) ) {
//                viewModel.loginApp().observe(getViewLifecycleOwner(), result -> {
//                    if (result) {
                        ActivityUtils.startActivity(new Intent(getActivity(), MainActivity.class));
                        getActivity().finish();
//                    }else{
//                        ActivityUtils.startActivity(new Intent(getActivity(), LoginActivity.class));
//                        getActivity().finish();
//                    }
//                });
            } else {
                ActivityUtils.startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
            }
        }, DELAY_TIME);
    }


    @Override
    protected void initObserver() {
        viewModel.error.observe(this, result -> {
            if (result) {
                ActivityUtils.startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
            }
        });
    }
}
